<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 11/14/18
 * Time: 7:54 PM
 */

namespace caroltc\jenkinsapp\util;


use caroltc\jenkinsapp\library\Facade;

trait RequestTool
{
    /**
     * 设置JSON返回格式
     * @param int $error_code
     * @param string $error_msg
     * @param array $ext_data
     * @return null
     */
    protected function setResult($error_code = 0, $error_msg = '', $ext_data = array())
    {
        $response = array();
        if (!empty($ext_data) && is_array($ext_data)) {
            $response = $ext_data;
        }
        if ($error_code == 0) {
            $response['status'] = 'OK';
        } else {
            $response['status'] = 'FAIL';
        }
        $response['error_code'] = $error_code;
        $response['msg'] = $error_msg;
        header('content-type:application/json;charset=utf8');

        $result = json_encode($response);
        if ($result === false) {
            $this->responseFail(5000, 'json encode error ' . json_last_error_msg());
        }
        Log::i('[return]' . $result);
        echo $result;
        if (Facade::isDebugMode()) {
            echo Log::getDebugData();
        }
        exit(0);
    }

    /**
     * 成功返回
     * @param array $data
     * @return null
     */
    protected function responseOk($data = array())
    {
        return $this->setResult('0', '', $data);
    }

    /**
     * 出错时返回
     * @param $error_code
     * @param string $error_msg
     * @param array $ext_data
     * @return null
     */
    protected function responseFail($error_code, $error_msg = '', $ext_data = array())
    {
        return $this->setResult($error_code, $error_msg, $ext_data);
    }

    /**
     * 检查参数不为空
     * @param $need_params
     * @param $request_data
     * @param array $can_empty_params
     * @return null
     */
    public function checkParams($need_params, $request_data = [], $can_empty_params = array())
    {
        $status = true;

        // check null
        if (empty($request_data)) {
            //$status = false;
            $request_data = $this->getAllRequestParams();
        }

        // check the param exist
        if ($status == true && !empty($request_data))
        {
            foreach ($need_params as $item)
            {
                if (!array_key_exists($item, $request_data))
                {
                    $status = false;
                    break;
                }
                if (!in_array($item, $can_empty_params)
                    && (
                        is_null($request_data[$item])
                        || $request_data[$item] === ''
                        || (is_array($item) && empty($item))
                    )) {
                    $status = false;
                    break;
                }
            }
        }

        if ($status == false) {
            return $this->responseFail('40000', '参数错误');
        }
        return null;
    }

    /**
     * 获取json数据
     * @return array|mixed
     */
    public function getJsonData()
    {
        header('Content-type: application/json');
        $result = json_decode(file_get_contents('php://input'), true);
        return is_array($result) ? $result : array();
    }

    /**
     * 安全的读取数据
     * @param $key
     * @param string $default
     * @param bool $check
     * @return string
     */
    public function getRequestParam($key, $default = '', $check = true)
    {
        if (isset($_GET[$key])) {
            return $this->safeCheck($_GET[$key], $check);
        }
        if (isset($_POST[$key])) {
            return $this->safeCheck($_POST[$key], $check);
        }
        $json_data = $this->getJsonData();
        if (isset($json_data[$key])) {
            return $this->safeCheck($json_data[$key], $check);
        }
        return $default;
    }

    /**
     * 获取全部请求的数据
     * @return array|mixed
     */
    public function getAllRequestParams()
    {
        $data = $this->getJsonData();
        if (isset($_GET) && !empty($_GET)) {
            $data = isset($_GET) && !empty($_GET) ? array_merge($data, $_GET) : $data;
        }
        if (isset($_POST) && !empty($_POST)) {
            $data = isset($_POST) && !empty($_POST) ? array_merge($data, $_POST) : $data;
        }
        return $data;
    }

    /**
     * 安全请求数据
     * @param $str
     * @param bool $check
     * @return string
     */
    public function safeCheck($str, $check = true)
    {
        if (is_array($str)) {
            return $str;
        }
        if (!$check) {
            return trim($str);
        }
        if (!get_magic_quotes_gpc()) // 判断magic_quotes_gpc是否打开
        {
            $str = addslashes($str); // 进行过滤
        }
//        $str = str_replace("_", "\_", $str); // 把 '_'过滤掉
//        $str = str_replace("%", "\%", $str); // 把' % '过滤掉
        $str = nl2br($str); // 回车转换
        $str= htmlspecialchars($str); // html标记转换
        return trim($str);
    }

}